package com.capinfo.controller;

import com.alibaba.fastjson.JSONObject;
import com.capinfo.base.BaseController;
import com.capinfo.base.CurrentUser;
import com.capinfo.entity.CapApprovalSuggestion;
import com.capinfo.entity.CapPreApproval;
import com.capinfo.entity.SysRoleUser;
import com.capinfo.entity.SysUser;
import com.capinfo.service.CapPreApprovalService;
import com.capinfo.service.CapServiceTypeService;
import com.capinfo.service.RoleUserService;
import com.capinfo.service.SysUserService;
import com.capinfo.util.CommonUtil;
import com.capinfo.util.JsonUtil;
import com.capinfo.util.ReType;
import com.capinfo.utils.ApprovalConstant;
import com.capinfo.utils.RedisUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author: sunbenjin
 * @date: 2020/2/27
 **/
@Controller
@RequestMapping(value = "/approval")
public class CapPreApprovalController extends BaseController {

    @Autowired
    private CapPreApprovalService capPreApprovalService;
    @Autowired
    private CapServiceTypeService capServiceTypeService;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RoleUserService roleUserService;

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/online_approval")
    @RequiresPermissions(value = "approval:select")
    public String onlineApproval(Model model){
        boolean approverRole = capPreApprovalService.isApproverRole(CommonUtil.getUser());
        model.addAttribute("approver",approverRole?"true":"false");
      return "online-approval";
    }

    @ApiOperation(value = "/approvalList", httpMethod = "GET", notes = "在线预审列表")
    @GetMapping("/approvalList")
    @ResponseBody
    public ReType approvalList(CapPreApproval capPreApproval,HttpServletRequest request, Model model, String page, String limit){
        CurrentUser user = CommonUtil.getUser();
        SysRoleUser sysRoleUser =  new SysRoleUser();
        sysRoleUser.setUserId(user.getId());
        sysRoleUser.setRoleId(ApprovalConstant.APPROVAL_ROLE_ID);
        int count = roleUserService.selectCountByCondition(sysRoleUser);
        //预审角色
        if(count>0){
            SysUser sysUser = sysUserService.selectByPrimaryKey(user.getId());
            String officeId = sysUser.getSysOffice();
            capPreApproval.setApprovalDept(officeId);
        }else{
            //用户角色
            capPreApproval.setCreateBy(user.getId());

        }

        List<CapPreApproval> tList = null;
        Page<CapPreApproval> tPage = PageHelper.startPage(Integer.valueOf(page),Integer.valueOf(limit));

        try {
            tList = capPreApprovalService.selectListByPage(capPreApproval);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ReType(tPage.getTotal(),tList);
    }
    @GetMapping("/add")
    @RequiresPermissions(value = "approval:add")
    public String add(Model model, CapPreApproval capPreApproval){
        if(StringUtils.isEmpty(capPreApproval.getApprovalNumber())){
            Map<String,String> map = capPreApprovalService.setSerialNo("YS",8);
            capPreApproval.setApprovalNumber(map.get("newOrderNo").toString());
            model.addAttribute("capPreApproval",capPreApproval);
        }
        boolean approverRole = capPreApprovalService.isApproverRole(CommonUtil.getUser());
        model.addAttribute("approver",approverRole?"true":"false");
        return "approval-form";
    }
    /**
     * 添加任务
     * @param capPreApproval
     * @return
     */
    @ApiOperation(value = "add" ,  httpMethod = "POST", notes = "添加预审saveActionFlag：空为保存，0提交，3取消预审")
    @PostMapping("add")
    @ResponseBody
    public JsonUtil saveCapPreApproval(CapPreApproval capPreApproval){
        JsonUtil j = new JsonUtil();
        try {
            capPreApprovalService.save(capPreApproval);
            j.setMsg("保存成功");
            j.setFlag(true);
        }catch (Exception e){
            j.setMsg("保存失败");
            j.setFlag(false);
            e.printStackTrace();
        }
        return j;
    }
    @GetMapping("/showApproval")
    @RequiresPermissions(value = "approval:select")
    public String showApproval(Model model,HttpServletRequest request){
        String id = request.getParameter("id");
        CapPreApproval capPreApproval = capPreApprovalService.selectByPrimaryKey(id);
        boolean approverRole = capPreApprovalService.isApproverRole(CommonUtil.getUser());
        model.addAttribute("approver",approverRole?"true":"false");
        model.addAttribute("capPreApproval",capPreApproval);
        String readonly = request.getParameter("detail");
        model.addAttribute("detail",readonly);
        return "approval-form";
    }

    @ApiOperation(value = "getApprovalSuggestionList" ,  httpMethod = "GET", notes = "获取预审意见")
    @GetMapping("getApprovalSuggestionList")
    @ResponseBody
    public JsonUtil getApprovalSuggestion(CapPreApproval capPreApproval){
        JsonUtil j = new JsonUtil();
        try {
            List<Object> list = redisUtils.lRange(capPreApproval.getId(),0,-1);
            if(!CollectionUtils.isEmpty(list)){

//             List<Object> sortList= list.stream().sorted((s1,s2)->
//                ((CapApprovalSuggestion)s1).getDate().compareTo(((CapApprovalSuggestion)s2).getDate())).collect(Collectors.toList());
                Object o = (Object) list;
                List<CapApprovalSuggestion> newList = (List<CapApprovalSuggestion>)o;
                List<CapApprovalSuggestion> sortList = newList.stream().sorted(Comparator.comparing(CapApprovalSuggestion::getDate).reversed()).collect(Collectors.toList());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("data",sortList);
                j.setJsonObj(jsonObject);
                j.setMsg("获取预审信息成功");
                j.setFlag(true);
            }else{
                j.setFlag(false);
                j.setMsg("无预审信息");
            }



        }catch (Exception e){
            j.setMsg("获取预审信息失败");
            j.setFlag(false);
            e.printStackTrace();
        }
        return j;
    }
    @ApiOperation(value = "addApprovalSuggestion" ,  httpMethod = "POST", notes = "（测试用）添加预审意见")
    @PostMapping("addApprovalSuggestion")
    @ResponseBody
    public JsonUtil addApprovalSuggestion(CapPreApproval capPreApproval){
        JsonUtil j = new JsonUtil();
        try {
           capPreApprovalService.setApprovalSuggestionToRedis(capPreApproval);
            j.setMsg("获取预审信息成功");
            j.setFlag(true);
        }catch (Exception e){
            j.setMsg("获取预审信息失败");
            j.setFlag(false);
            e.printStackTrace();
        }
        return j;
    }
    @ApiOperation(value = "unSign" ,  httpMethod = "POST", notes = "预审解答")
    @PostMapping("unSign")
    @ResponseBody
    public JsonUtil unSign(CapPreApproval capPreApproval){
        JsonUtil j = new JsonUtil();
        try {
            capPreApproval = capPreApprovalService.selectByPrimaryKey(capPreApproval);
            if(capPreApproval!=null){
                String userId = CommonUtil.getUser().getId();
                capPreApproval.setTaskStatus(ApprovalConstant.TASKSTATUS[0]);
                capPreApproval.setApprovalPerson(null);
                capPreApproval.setUpdateDate(new Date());
                capPreApproval.setUpdateBy(userId);
                capPreApprovalService.updateByPrimaryKeySelective(capPreApproval);
                j.setMsg("解签成功");
                j.setFlag(true);
            }else{
                j.setFlag(false);
                j.setMsg("解签失败");
            }

        }catch (Exception e){
            j.setMsg("解签失败");
            j.setFlag(false);
            e.printStackTrace();
        }
        return j;
    }
    @ApiOperation(value = "sign" ,  httpMethod = "POST", notes = "预审签收")
    @PostMapping("sign")
    @ResponseBody
    public JsonUtil sign(CapPreApproval capPreApproval){
        JsonUtil j = new JsonUtil();
        try {
            capPreApproval = capPreApprovalService.selectByPrimaryKey(capPreApproval);
            if(capPreApproval!=null){
                String userId = CommonUtil.getUser().getId();
                capPreApproval.setTaskStatus(ApprovalConstant.TASKSTATUS[1]);
                capPreApproval.setApprovalPerson(userId);
                capPreApproval.setUpdateDate(new Date());
                capPreApproval.setUpdateBy(userId);
                capPreApprovalService.updateByPrimaryKeySelective(capPreApproval);
                j.setMsg("签收成功");
                j.setFlag(true);
            }else{
                j.setFlag(false);
                j.setMsg("签收失败");
            }

        }catch (Exception e){
            j.setMsg("签收失败");
            j.setFlag(false);
            e.printStackTrace();
        }
        return j;
    }

}
